XOR “Encryption” in C: An Old Trick and an Inside Joke

This example began as an inside joke with my boss: if we were going to add encryption, why not use one of the oldest tricks still rattling around the toolbox? XOR is a useful way to learn how bytes and reversible transformations work, but a fixed repeating key does not provide meaningful security.

The XOR Transformation


#include <stdio.h>
#include <string.h>

#define KEY 0xAA // Simple XOR key

// Function to encrypt and decrypt data using XOR
void xor_encrypt_decrypt(char *data, size_t len, char key) {
    for (size_t i = 0; i < len; i++) {
        data[i] ^= key;
    }
}

int main() {
    char message[] = "Hello, World!";
    size_t len = strlen(message);

    printf("Original message: %s\n", message);

    // Encrypt the message
    xor_encrypt_decrypt(message, len, KEY);
    printf("Encrypted message: %s\n", message);

    // Decrypt the message
    xor_encrypt_decrypt(message, len, KEY);
    printf("Decrypted message: %s\n", message);

    return 0;
}

Let's break down the code:

Compiling and Running the Code

To compile and run the provided C source code for the ARM64 architecture, follow these steps:


# Compile the code
gcc -o xor_encryption xor_encryption.c

# Run the code
./xor_encryption

This compiles the XOR example and displays the original, transformed, and restored messages. The same operation reverses itself because A XOR K XOR K equals A.

Where Real Encryption Begins

Modern applications need authenticated encryption: confidentiality plus a reliable way to detect modification. They also need unique nonces and keys generated from a cryptographically secure source. The next article,